package com.wechat.bot.Consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.wechat.bot.common.log.Log;
import com.wechat.bot.entity.Bot;
import com.wechat.bot.entity.WarningInfo;
import com.wechat.bot.msg.TextMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author zhangyanan
 * @date 2022/9/30 16:15
 * @description
 */
@Component
public class HelloConsumer {


    private static final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Value("${spring.rabbitmq.queue}")
    String queuename;

    @Value("${bot.name}")
    String botname;

    public static void main(String[] args) throws ParseException {
        HelloConsumer helloConsumer = new HelloConsumer();
        System.out.println(helloConsumer.dayAd8("2022-01-01 00:00:00"));
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public String dayAd8(String d) throws ParseException {
        Date parse = null;
        parse = simpleDateFormat.parse(d);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(parse);
        calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR) + 8);
        return simpleDateFormat.format(calendar.getTime());
    }

    @RabbitListener(queues = "queue.warninfo.publish")
    public void onMessage(Message message, final Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws Exception {
        try {
            String payload = message.getPayload().toString();
            System.out.println("消息队列推送来的消息：" + payload);
            WarningInfo[] warningInfo = JSONObject.parseObject(payload, WarningInfo[].class);
            Map<String, Properties> dispatchConf = com.wechat.bot.config.ConfigManagement.readIniConf("config/warn.ini");
            int count = 1;
            String messages = "";
            for (int i = 0; i < warningInfo.length; i++) {
                WarningInfo info = warningInfo[i];
                Properties text = dispatchConf.get("text");
                String msg = text.getProperty("ass");
                msg = msg.replaceAll("name", info.getName());
                msg = msg.replaceAll("fiat_price_range", info.getFiat_price_range());
                msg = msg.replaceAll("recent_transaction_fiat_price_str", info.getRecent_transaction_fiat_price_str());

                double ratio = Double.parseDouble(info.getFiat_price_range().split(" ")[0]);
                double recentPrice = Double.parseDouble(info.getRecent_transaction_fiat_price_str().split(" ")[0]);
                double percentage = ratio / recentPrice * 100;
                msg = msg.replaceAll("percentage", String.valueOf(percentage));
                String format = f.format(new Date());
                msg = msg.replaceAll("datetime", dayAd8(format));
                String messageWithIndex = count + "." + msg;
                messages += messageWithIndex+"\n";
                count  = count + 1;
                Log.info("message:" + messages);
                Log.info("count:" + count);
                if (count == 6 || i == warningInfo.length - 1) {
                    messages += "【交易有风险，投资需谨慎！】";
                    TextMsg textMsg = new TextMsg();
                    textMsg.setContent(messages);
                    Log.info("" + textMsg.getContent());
                    textMsg.setMentionedList(Collections.singletonList("@all"));
                    Bot bot = new Bot(botname);
                    Boolean send = bot.send(textMsg);
                    Log.info("推送的对象：" + messages);
                    Log.info("推送成功");
                    messages = "";
                    count = 1;
                }
            }
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            Log.info("Error:"+e.getMessage());
            /*
            * basicNack()方法的第一个参数是消息的delivery tag，通过delivery.getEnvelope().getDeliveryTag()获取。第二个参数是multiple标识，
            * 表示是否批量拒绝，这里设为false表示只拒绝当前一条消息。第三个参数是requeue标识，表示是否重新放回队列，这里设为true表示重新放回队列等待处理。
            *
            * */
            channel.basicNack(deliveryTag, false, true);
        }

    }
}
